//
//  AuthenictateInfoViewController.m
//  QRMaster
//
//  Created by myApple on 16/4/12.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "AuthenictateInfoViewController.h"
#import "AreaChooseController.h"
#import "RequestNetWork.h"
#import "AuthenicateInfoHeadView.h"
#import "validateInputValue.h"
#import "IQTextView.h"
#import "IQKeyboardManager.h"

@interface AuthenictateInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate,UITextViewDelegate,UITextViewDelegate>
{
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UITableView * infoTableView;
    NSArray * headTitelArray;
    UITextField * communityTextField;
    UILabel * foreignLabel;
    UILabel * noForeignLabel;
    UIScrollView * communityScrollView;
    UITextField * contactTextField;
    UITextField * mobileTextField;
    UIButton * areaCodeBtn;
    IQTextView * addressTextView;
    //是否有改变
    BOOL flag;
    BOOL communityTextFieldFlag;
    BOOL contractTextFieldFlag;
    BOOL mobileTextFieldFlag;
    BOOL addressTextFieldFlag;
    AuthenBaseInfoModel * baseInfoModel;
    
}

@end

@implementation AuthenictateInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"authenInfo", @"基本信息");
    headTitelArray = @[NSLocalizedString(@"companyName",@"企业名称"),NSLocalizedString(@"isForeign",@"是否外籍"),NSLocalizedString(@"represent",@"法人代表"),NSLocalizedString(@"telePhoneNum",@"手机号码"),NSLocalizedString(@"address",@"地址")];
    [self prepareView];
    [self prepareTableView];
    
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submit)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
}

-(void)prepareView
{
    communityTextField = [[UITextField alloc]initWithFrame:CGRectMake(22, 13, UI_SCREEN_WIDTH - 22, 15)];
    communityTextField.font = [UIFont systemFontOfSize:15.0];
    communityTextField.textColor = UIColorFromRGB(0x333333);
    communityTextField.delegate = self;
    communityTextField.placeholder = NSLocalizedString(@"input", @"请输入...");
    communityTextField.font = [UIFont systemFontOfSize:15.0];
    communityTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    foreignLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, 13, UI_SCREEN_WIDTH - 22, 15)];
    foreignLabel.textColor = UIColorFromRGB(0x333333);
    foreignLabel.font = [UIFont systemFontOfSize:15.0];
    foreignLabel.text = NSLocalizedString(@"yes", @"是");
    
    noForeignLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, 13, UI_SCREEN_WIDTH - 22, 15)];
    noForeignLabel.textColor = UIColorFromRGB(0x333333);
    noForeignLabel.font = [UIFont systemFontOfSize:15.0];
    noForeignLabel.text = NSLocalizedString(@"not", @"否");
    
    contactTextField = [[UITextField alloc]initWithFrame:CGRectMake(22, 13, UI_SCREEN_WIDTH - 22, 15)];
    contactTextField.font = [UIFont systemFontOfSize:15.0];
    contactTextField.textColor = UIColorFromRGB(0x333333);
    contactTextField.delegate = self;
    contactTextField.placeholder = NSLocalizedString(@"input", @"请输入...");
    contactTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    areaCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    areaCodeBtn.frame = CGRectMake(22, 0, 50, 40);
    [areaCodeBtn addTarget:self action:@selector(changeAreaCode) forControlEvents:UIControlEventTouchUpInside];
    areaCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    areaCodeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
    [areaCodeBtn setTitleColor:UIColorFromRGB(0x333333) forState:0];
    
    mobileTextField = [[UITextField alloc]initWithFrame:CGRectMake(85, 13, UI_SCREEN_WIDTH - 85, 15)];
    mobileTextField.textColor = UIColorFromRGB(0x333333);
    mobileTextField.placeholder = NSLocalizedString(@"input", @"请输入...");
    mobileTextField.font = [UIFont systemFontOfSize:15.0];
    mobileTextField.borderStyle = UITextBorderStyleNone;
    mobileTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    mobileTextField.keyboardType = UIKeyboardTypeNumberPad;
    mobileTextField.delegate = self;
    
    addressTextView = [[IQTextView alloc]initWithFrame:CGRectMake(22, 0, UI_SCREEN_WIDTH - 22, 80)];
    addressTextView.font = [UIFont systemFontOfSize:15.0];
    addressTextView.textColor = UIColorFromRGB(0x333333);
    addressTextView.delegate = self;
    addressTextView.placeholder = NSLocalizedString(@"input", @"请输入...");
    addressTextView.showsVerticalScrollIndicator = NO;
    addressTextView.keyboardType = UIKeyboardAppearanceDefault;
    addressTextView.returnKeyType = UIReturnKeyDone;
}


-(void)prepareTableView
{
    infoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 5, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT - 64 - 5) style:UITableViewStyleGrouped];
    infoTableView.dataSource = self;
    infoTableView.delegate = self;
    infoTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:infoTableView];
}

-(void)setInfoModel:(AuthenBaseInfoModel *)infoModel
{
     flag = NO;
    _infoModel = infoModel;
    baseInfoModel = [infoModel copy];
    flag = infoModel.foreign;
    [infoTableView reloadData];
}


#pragma mark ----------- UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_infoModel.authType == 1) {
        return 5;
    }
    else
    {
        return 1;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return 2;
    }
    else
    {
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 4) {
        return 80;
    }
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellId =  @"cellId";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    cell.backgroundColor = [UIColor whiteColor];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId
                ];
    }
    if (indexPath.section == 0) {
        communityTextField.text = baseInfoModel.name;
        [cell addSubview:communityTextField];
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            if (flag) {
                [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            }
            else
            {
                [cell setAccessoryType:UITableViewCellAccessoryNone];
            }
            [cell addSubview:foreignLabel];
        }
        else
        {
            if (!flag) {
                [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            }
            else
            {
                [cell setAccessoryType:UITableViewCellAccessoryNone];
            }
            [cell addSubview:noForeignLabel];
        }

    }
   else if (indexPath.section == 2) {
        contactTextField.text = baseInfoModel.corporation;
        [cell addSubview:contactTextField];
    }
    else if (indexPath.section == 3)
    {
         [areaCodeBtn setTitle:[NSString stringWithFormat:@"+%@",baseInfoModel.areaCode] forState:0];
        [cell addSubview:areaCodeBtn];
         mobileTextField.text = baseInfoModel.mobile;
        [cell addSubview:mobileTextField];
    }
   else if (indexPath.section == 4) {
       addressTextView.text = baseInfoModel.address;
       [cell addSubview:addressTextView];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 33.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    AuthenicateInfoHeadView * headView = [[AuthenicateInfoHeadView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 33)];
    if (_infoModel.authType == 1) {
        headView.titleName = headTitelArray[section];
    }
    else
    {
        headView.titleName = NSLocalizedString(@"authenName", @"姓名");
    }
    return headView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        [self.view endEditing:YES];
        if (indexPath.row == 0) {
            flag = YES;
        }
        else
        {
            flag = NO;
        }
        [tableView reloadData];
        [self enableOrNotSubmit];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark ----------- UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == communityTextField) {
        if ([newString isEqualToString:_infoModel.name]) {
            communityTextFieldFlag = NO;
        }
        else
        {
            communityTextFieldFlag = YES;
        }
       baseInfoModel.name = newString;
    }
    else if (textField == contactTextField)
    {
        if ([newString isEqualToString:_infoModel.corporation]) {
            contractTextFieldFlag = NO;
        }
        else
        {
            contractTextFieldFlag = YES;
        }
        baseInfoModel.corporation = newString;
    }else if (textField == mobileTextField)
    {
        if ([newString isEqualToString:_infoModel.mobile]) {
            mobileTextFieldFlag = NO;
        }
        else
        {
            mobileTextFieldFlag = YES;
        }
        baseInfoModel.mobile = newString;
    }
    [self enableOrNotSubmit];
    return YES;

}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == communityTextField) {
        baseInfoModel.name = textField.text;
    }
    else if (textField == contactTextField)
    {
        baseInfoModel.corporation = textField.text;
    }else if (textField == mobileTextField)
    {
        baseInfoModel.mobile = textField.text;
    }
    [self enableOrNotSubmit];
}

#pragma mark ----------- UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
      NSString * newString = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if ([newString isEqualToString:_infoModel.address]) {
        addressTextFieldFlag = NO;
    }
    else
    {
        addressTextFieldFlag = YES;
    }
    if ([@"\n"isEqualToString:text] == YES) {
        [textView resignFirstResponder];
        return NO;
    }
    baseInfoModel.address = newString;
    addressTextView.frame = CGRectMake(addressTextView.frame.origin.x, addressTextView.frame.origin.y, addressTextView.frame.size.width, textView.contentSize.height);
     [self enableOrNotSubmit];
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:_infoModel.address]) {
        addressTextFieldFlag = NO;
    }
    else
    {
        addressTextFieldFlag = YES;
    }
    baseInfoModel.address = textView.text;
    [self enableOrNotSubmit];
}


-(void)enableOrNotSubmit
{
    if (addressTextFieldFlag || mobileTextFieldFlag || contractTextFieldFlag || communityTextFieldFlag || (_infoModel.foreign != flag)||![baseInfoModel.areaCode isEqualToString:_infoModel.areaCode]) {
        [self submitEnableOrNot:YES];
    }
    else
    {
        [self submitEnableOrNot:NO];
    }
}

#pragma mark --------- 切换时区
-(void)changeAreaCode
{
    [self.view endEditing:YES];
    AreaChooseController * areaVC = [[AreaChooseController alloc]init];
    [self.navigationController pushViewController:areaVC animated:YES];
    areaVC.areaCode = ^(NSString * areaCodeId,NSString * areaOrCountry)
    {
        [areaCodeBtn setTitle:[NSString stringWithFormat:@"+%@",areaCodeId] forState:0];
        baseInfoModel.areaCode = areaCodeId;
        [self enableOrNotSubmit];
    };
}

#pragma mark --------- 完成按钮是否可以点击
-(void)submitEnableOrNot:(BOOL)flags
{
    submitImageView.userInteractionEnabled = flags;
    if (flags) {
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    }
    else
    {
         submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    }
}

#pragma mark ---------- 完成
-(void)submit
{
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    if (_infoModel.status == 2 || _infoModel.status == 3) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"feedBackAlterPromt", @"提示") message:NSLocalizedString(@"modifyAuthenPromt", @"改物业认证资料将重新审核，审核期间锁掌柜不可用")  delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消") otherButtonTitles:NSLocalizedString(@"alterSure",@"确认"), nil];
        [alertView show];
    }
    else
    {
        [self postNetwork];
    }
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self postNetwork];
    }
}

-(void)postNetwork
{
    if ([self IsHaveNetwork]) {
        return;
    }
    if (![self checkInput]) {
        return;
    }
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    if (_infoModel.authType == 1) {
        [postDict setValue:communityTextField.text forKey:@"name"];
        [postDict setValue:(flag == YES?@"1":@"0") forKey:@"foreign"];
        [postDict setValue:addressTextView.text forKey:@"address"];
        [postDict setValue:contactTextField.text forKey:@"corporation"];
        [postDict setValue:[areaCodeBtn.titleLabel.text substringFromIndex:1] forKey:@"areaCode"];
        [postDict setValue:mobileTextField.text forKey:@"mobile"];
    }
    else
    {
        [postDict setValue:communityTextField.text forKey:@"name"];
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [self startWaiting:nil color:nil addToView:self.view];
    __weak AuthenictateInfoViewController * weakSelf = self;
    [rnk initWithPath:POST(SAVEAUTHINFO) params:postDict block:^(id downLoadData, id error) {
        [weakSelf stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            weakSelf.infoModel = baseInfoModel;
            if (weakSelf.info) {
                weakSelf.info(weakSelf.infoModel);
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }
        
    }];
}

-(BOOL)checkInput
{
    if (_infoModel.authType == 2) {
        if ([validateInputValue validateStringIsNull:communityTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"nameEmpty",@"名称不能为空") superView:self.view];
            return NO;
        }
        if (![validateInputValue validateStringLength:communityTextField.text minLength:1 maxLength:20]) {
            [PromptInfoView showMessage: NSLocalizedString(@"nameLengthError",@"名称长度不能超过20个字符") superView:self.view];
            return NO;
        }
        
    }
    if (_infoModel.authType == 1) {
        if ([validateInputValue validateStringIsNull:communityTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"nameEmpty",@"名称不能为空") superView:self.view];
            return NO;
        }
        if (![validateInputValue validateStringLength:communityTextField.text minLength:1 maxLength:50]) {
            [PromptInfoView showMessage: NSLocalizedString(@"companyNameError",@"名称长度不能超过50个字符") superView:self.view];
            return NO;
        }
        if ([validateInputValue validateStringIsNull:contactTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"representEmpty",@"法人代表不能为空") superView:self.view];
            return NO;
        }
        if (![validateInputValue validateStringLength:contactTextField.text minLength:1 maxLength:255]) {
            [PromptInfoView showMessage:NSLocalizedString(@"representError",@"法人代表长度不能大于255个字符")superView:self.view];
            return NO;
        }
        if ([validateInputValue validateStringIsNull:mobileTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"mobileEmpty",@"电话不能为空") superView:self.view];
            return NO;
        }
        if (![validateInputValue isPureNumandCharacters:mobileTextField.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"errorTelePhone", @"电话格式有误") superView:self.view];
            return NO;
        }
        if ([validateInputValue validateStringIsNull:addressTextView.text]) {
            [PromptInfoView showMessage:NSLocalizedString(@"addressEmpty",@"地址不能为空") superView:self.view];
            return NO;
        }
        if (![validateInputValue validateStringLength:addressTextView.text minLength:1 maxLength:255]) {
            [PromptInfoView showMessage:NSLocalizedString(@"addressLengthError",@"地址长度不能大于255个字符") superView:self.view];
            return NO;
        }
    }
    return YES;
}

#pragma mark ----------- 根据字符算宽度
-(float)calculateWidth:(NSString *)str
{
     NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:25],};
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(10000, 40) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    float width = textSize.width;
    return width;
}

#pragma mark ----------- 根据字符算高度
-(float)calculateHeight:(NSString *)str
{
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0],};
    CGSize textSize = [str boundingRectWithSize:CGSizeMake(addressTextView.frame.size.width, 1000) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    float height = textSize.height;
    return height;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
